<template>
  <div id="goodsPage">
    <el-row type="flex" justify="start" style="width: 100%; margin-bottom: 20px">
      <!-- 搜索区域 -->
      <el-col :span="24">
        <el-card>
          <el-form ref="searchFormComponents" :model="searchForm" inline>
            <el-row :gutter="10">
              <el-col :span="4">
                <el-form-item label="货物名称" prop="name">
                  <el-input
                      v-model="searchForm.name"
                      clearable
                      placeholder="货物名称"
                      style="width: 100%"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="货物类型" prop="type">
                  <el-input
                      v-model="searchForm.type"
                      clearable
                      placeholder="货物类型"
                      style="width: 100%"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="货物批次" prop="code">
                  <el-input
                      v-model="searchForm.code"
                      clearable
                      placeholder="货物批次"
                      style="width: 100%"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="状态" prop="state">
                  <el-select
                      v-model="searchForm.state"
                      placeholder="请选择"
                      clearable
                      filterable
                      style="width: 100%"
                  >
                    <el-option :label="item" :value="item" :key="item" v-for="item in stateList"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4" class="search-button-col">
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
                  <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

        </el-card>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-card>
      <el-table
          :data="listData"
          style="width: 100%"
          v-loading="loading"
          tooltip-effect="dark"
          border
          :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
          @selection-change="handleSelectionChange"
      >
        <!-- 多选列 -->
        <el-table-column
            type="selection"
            width="55"
            align="center"
            fixed="left"
        ></el-table-column>

        <!-- 隐藏的货物ID列 -->
        <el-table-column
            prop="gid"
            label="货物ID"
            width="0"
            v-if="false"
            align="center"
        ></el-table-column>
        <!-- 表头 -->
        <!-- 序号列 -->
        <el-table-column
            type="index"
            label="序号"
            width="80"
            :index="calculateIndex"
            align="center"
        ></el-table-column>

        <!-- 货物名称 -->
        <el-table-column
            prop="name"
            label="货物名称"
            show-overflow-tooltip
            width="120"
            align="center"
        ></el-table-column>

        <!-- 货物类型 -->
        <el-table-column
            prop="type"
            label="货物类型"
            show-overflow-tooltip
            align="center"
            width="100"
        ></el-table-column>

        <!-- 单个货物面积 -->
        <el-table-column
            prop="area"
            label="单个面积"
            show-overflow-tooltip
            align="center"
            width="100"
        ></el-table-column>

        <!-- 单个货物价值 -->
        <el-table-column
            prop="money"
            label="单个价值"
            show-overflow-tooltip
            align="center"
            width="100"
        ></el-table-column>

        <!-- 实际货物数量 -->
        <el-table-column
            prop="nowNum"
            label="货物数量"
            show-overflow-tooltip
            align="center"
            width="100"
        ></el-table-column>
        <!-- 实际货物入库数量 -->
        <el-table-column
            prop="initNum"
            label="入库数量"
            show-overflow-tooltip
            align="center"
            width="100"
        ></el-table-column>

        <!-- 货物批次 -->
        <el-table-column
            prop="code"
            label="货物批次"
            show-overflow-tooltip
            align="center"
            width="120"
        ></el-table-column>

        <!-- 货物状态 -->
        <el-table-column
            label="货物状态"
            prop="state"
            show-overflow-tooltip
            align="center"
            width="100"
        ></el-table-column>

        <!-- 货物存放时长 -->
        <el-table-column
            prop="time"
            label="存放时长（天）"
            show-overflow-tooltip
            width="120"
            align="center"
        ></el-table-column>

        <!-- 操作列 -->
        <el-table-column
            fixed="right"
            label="操作"
            width="280"
            align="center"
        >
          <template slot-scope="scope">
            <el-button
                v-if="scope.row.state === '待入库'"
                @click="handleEdit(scope.row)"
                type="primary"
                size="mini"
                class="action-button"
            >
              <i class="el-icon-edit"></i> 入库
            </el-button>
            <el-button
                v-if="['已入库','快逾期','逾期','待出库'].includes(scope.row.state)"
                type="danger"
                @click="handleDelete(scope.row)"
                size="mini"
                class="action-button"
            >
              <i class="el-icon-delete"></i> 出库
            </el-button>
            <el-button
                v-if="scope.row.state === '已入库'"
                type="danger"
                @click="handleMove(scope.row)"
                size="mini"
                class="action-button"
            >
              <i class="el-icon-delete"></i> 移库
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="searchForm.current"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="searchForm.pageSize"
            :total="searchForm.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 入库模态框 -->
    <el-dialog
        :visible.sync="warehouseDialogVisible"
        title="选择入库位置"
        width="600px"
        :before-close="handleWarehouseClose"
    >
      <template>
        <el-form :model="warehouseForm" :rules="warehouseRules" ref="warehouseFormRef" label-width="100px">
          <el-form-item label="仓库" prop="warehouseId">

            <el-select
                v-model="warehouseForm.warehouseId"
                placeholder="请选择仓库"
                @change="onWarehouseChange"
                clearable
                style="width: 100%"
            >
              <el-option
                  v-for="warehouse in warehouseList"
                  :key="warehouse.wid"
                  :label="warehouse.name"
                  :value="warehouse.wid"
              ></el-option>
            </el-select>


          </el-form-item>

          <el-form-item label="区域" prop="areaId">
            <el-select
                v-model="warehouseForm.areaId"
                placeholder="请选择区域"
                @change="onAreaChange"
                :disabled="!warehouseForm.warehouseId"
                clearable
                style="width: 100%"
            >
              <el-option
                  v-for="item in areaList"
                  :key="item.id"
                  :label="item.r_name"
                  :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="仓位" prop="positionId">
            <!-- 修改为多选框 -->
            <el-checkbox-group v-model="warehouseForm.positionId">
              <el-checkbox
                  v-for="item in positionList"
                  :key="item.id"
                  :label="item.id"
                  :disabled="item.state == 1"
              style="display: block; margin-bottom: 8px;"
              >
              {{ item.type.rTypeName || '未知类型' }} - {{ item.location || '未知位置' }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="入库数量" prop="quantity">
            <el-input-number
                v-model="warehouseForm.quantity"
                :min="1"
                :max="currentGoods.maxQuantity"
                :precision="0"
                size="small"
                style="width: 100%"
            ></el-input-number>
            <div style="color: #888; font-size: 12px; margin-top: 5px;">
              可入库最大数量: {{ currentGoods.maxQuantity }}
            </div>
          </el-form-item>
        </el-form>
      </template>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="warehouseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitWarehouseForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 出库模态框 -->
    <el-dialog
        :visible.sync="outDialogVisible"
        title="货物出库"
        width="400px"
    >
      <el-form :model="outForm" :rules="outRules" ref="outFormRef" label-width="100px">
        <el-form-item label="出库数量" prop="quantity">
          <el-input-number
              v-model="outForm.quantity"
              :min="1"
              :max="outForm.maxQuantity"
              :precision="0"
              controls-position="right"
              style="width: 100%"
          ></el-input-number>
          <div style="color: #888; font-size: 12px; margin-top: 5px;">
            当前库存: {{ outForm.maxQuantity }}
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
    <span class="dialog-footer">
      <el-button @click="outDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitOutForm">确定</el-button>
    </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  data() {
    return {
      // 表格数据
      listData: [],
      // 多选存储
      selectedItems: [],
      // 货物状态参数
      stateList: ['待入库', '待出库', '快逾期','逾期','已入库','已出库'],
      // 规则
      rules: {},
      // 查询参数
      searchForm: {
        name: '',  // 货物名称搜索
        type: '',  // 货物类型搜索
        code: '',  // 货物批次搜索
        state: '', // 货物状态搜索
        gid: '',
        // 分页参数
        current: 1,   // 当前页
        pageSize: 10, // 每页容量
        total: 0
      },
      loading: false,

      // 仓库选择模态框相关数据
      warehouseDialogVisible: false,
      warehouseForm: {
        warehouseId: '',
        areaId: '',
        positionId: [],
        quantity: 1,//默认货物全部入库
      },
      warehouseRules: {
        warehouseId: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        areaId: [
          { required: true, message: '请选择区域', trigger: 'change' }
        ],
        positionId: [
          {
            type: 'array', required: true, min: 1, message: '请至少选择一个仓位', trigger: 'change',
            validator: (rule, value, callback) => {
              // 只有选择了区域后才验证仓位
              if (this.warehouseForm.areaId && (!value || value.length === 0)) {
                callback(new Error('请至少选择一个仓位'));
              } else {
                callback();
              }
            }
          }
        ],
        quantity: [
          { required: true, message: '请输入入库数量', trigger: 'blur' },
          { type: 'number', message: '入库数量必须为数字值', trigger: 'blur' }
        ]
      },
      warehouseList: [],
      areaList: [],
      positionList: [],
      currentGoods: {
        maxQuantity:0
      },
      // 出库相关数据
      outDialogVisible: false,
      outForm: {
        gid: '',
        quantity: 1,
        maxQuantity: 0
      },
      outRules: {
        quantity: [
          { required: true, message: '请输入出库数量', trigger: 'blur' },
          { type: 'number', min: 1, message: '出库数量必须大于0', trigger: 'blur' }
        ]
      },
      loadingWarehouse: false,
      loadingArea: false,
      loadingPosition: false
    }
  },
  mounted() {
    // 获取表格数据
    this.getGoodsInfo();
  },
  methods: {
    // 获取表格信息
    getGoodsInfo() {
      this.loading = true
      request.post('/goods/get/getGoods', {
        ...this.searchForm,
      })
          .then(response => {
            console.log(response.data.data.data.list)
            // 响应结果有个data属性，存的是接口返回的数据，所以多个data
            this.listData = response.data.data.data.list;
            this.searchForm.total = response.data.data.data.total;
            this.loading = false
          })
          .catch(error => {
            console.error('获取货物信息列表失败:', error);
            this.$message.error('获取货物信息列表失败');
            this.loading = false;
          });
    },
    // 查询
    search() {
      this.searchForm.current = 1;
      this.getGoodsInfo();
    },
    // 重置搜索框
    resetSearch() {
      // 重置表单字段
      this.$refs.searchFormComponents.resetFields();
      // 重置分页到第一页
      this.searchForm.current = 1;
      // 重新获取数据
      this.getGoodsInfo();
    },
    // 分页
    handleSizeChange(newSize) {
      this.searchForm.pageSize = newSize;
      this.searchForm.current = 1;
      this.getGoodsInfo();
    },
    handleCurrentChange(newPage) {
      this.searchForm.current = newPage;
      this.getGoodsInfo();
    },
    // 处理多选
    handleSelectionChange(val) {
      this.selectedItems = val;
    },
    // 添加计算表格索引的方法
    calculateIndex(index) {
      return (this.searchForm.current - 1) * this.searchForm.pageSize + index + 1;
    },

    // 入库操作
    handleEdit(row) {
      console.log('选中的货物:', row);  // 添加日志
      this.currentGoods = {
        ...row,
        maxQuantity: row.nowNum - (row.initNum || 0)
      };
      // 初始化入库数量为可入库的最大数量
      this.warehouseForm.quantity = Math.min(1, this.currentGoods.maxQuantity);

      this.resetWarehouseForm();
      this.warehouseDialogVisible = true;
      this.loadWarehouseList();
    },

    // 出库操作
    handleDelete(row) {
      this.outDialogVisible = true;
      this.outForm = {
        gid: row.gid,
        quantity: row.nowNum, // 默认出库全部数量
        maxQuantity: row.nowNum // 最大可出库数量
      };
    },

    // 移库操作
    handleMove(row) {
      // 移库逻辑，可以复用入库的模态框，只需要修改API调用
      console.log('移库:', row);
      this.currentGoods = row;
      this.resetWarehouseForm();
      this.warehouseDialogVisible = true;
      this.loadWarehouseList();
    },

    // 加载仓库列表
    loadWarehouseList() {
      if (!this.currentGoods || !this.currentGoods.type) {
        this.$message.warning('无法获取货物类型信息');
        return;
      }

      console.log('加载仓库列表，货物类型:', this.currentGoods.type);  // 添加日志
      this.loadingWarehouse = true;
      request.get('/good/getWarehousesByType', {
        params: {
          type: this.currentGoods.type  // 修改为type
        }
      })
          .then(response => {
            console.log('仓库列表响应:', response.data.data.list);  // 添加日志
            if (response.data.code === '200') {
              this.warehouseList = response.data.data.list || [];

              console.log(this.warehouseList)
              if (this.warehouseList.length === 0) {
                this.$message.info('没有找到适合此类型货物的仓库');
              }
            } else {
              this.$message.error(response.data.message || '获取仓库列表失败');
            }
            this.loadingWarehouse = false;
          })
          .catch(error => {
            console.error('获取仓库列表失败:', error);
            this.$message.error('获取仓库列表失败');
            this.loadingWarehouse = false;
          });
    },

    // 仓库选择变化
    onWarehouseChange(warehouseId) {
      console.log('选中的仓库ID:', warehouseId);  // 添加日志
      this.warehouseForm.areaId = '';
      this.warehouseForm.positionId = '';
      this.areaList = [];
      this.positionList = [];

      if (warehouseId) {
        this.loadAreaList(warehouseId);
      }
    },

    // 区域选择变化
    onAreaChange(areaId) {
      console.log('选中的区域ID:', areaId);  // 添加日志
      this.warehouseForm.positionId = [];
      this.positionList = [];

      if (areaId) {
        this.loadPositionList(areaId);
      }
    },

    // 加载区域列表
    loadAreaList(warehouseId) {
      console.log('加载区域列表，仓库ID:', warehouseId);  // 添加日志
      this.loadingArea = true;
      request.get('/good/getRegionByWid', {
        params: {
          wid: warehouseId
        }
      })
          .then(response => {
            console.log('区域列表响应:', response.data.data);  // 添加日志
            if (response.data.code === '200') {
              this.areaList = response.data.data.list || [];
            } else {
              this.$message.error(response.data.message || '获取区域列表失败');
            }
            this.loadingArea = false;
          })
          .catch(error => {
            console.error('获取区域列表失败:', error);
            this.$message.error('获取区域列表失败');
            this.loadingArea = false;
          });
    },

    // 加载仓位列表
    loadPositionList(areaId) {
      console.log('加载仓位列表，区域ID:', areaId);  // 添加日志
      this.loadingPosition = true;
      request.get('/good/positionList', {
        params: {
          r_id :areaId
        }
      })
          .then(response => {
            console.log('仓位列表响应:', response.data.data.list);  // 添加日志
            if (response.data.code === '200') {
              this.positionList = response.data.data.list|| [];
            } else {
              this.$message.error(response.data.message || '获取仓位列表失败');
            }
            this.loadingPosition = false;
          })
          .catch(error => {
            console.error('获取仓位列表失败:', error);
            this.$message.error('获取仓位列表失败');
            this.loadingPosition = false;
          });
    },

    // 重置入库表单
    resetWarehouseForm() {
      this.warehouseForm = {
        warehouseId: '',  // 修改为warehouseId
        areaId: '',
        positionId: [],
        quantity: 1,
      };
      this.areaList = [];
      this.positionList = [];

      if (this.$refs.warehouseFormRef) {
        this.$refs.warehouseFormRef.resetFields();
      }
    },

    // 关闭入库模态框
    handleWarehouseClose(done) {
      this.$confirm('确认关闭吗？未提交的信息将丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.resetWarehouseForm();
        done();
      }).catch(() => {
        // 取消关闭
      });
    },

    // 提交入库表单
    submitWarehouseForm() {
      this.$refs.warehouseFormRef.validate((valid) => {
        if (valid) {
          console.log('提交入库表单:', this.warehouseForm);  // 添加日志
          // 执行入库API调用
          const params = {
            gbatch: this.currentGoods.code,
            wid: this.warehouseForm.warehouseId,
            id: this.warehouseForm.areaId,
            positionIds: this.warehouseForm.positionId,
            gnum: this.warehouseForm.quantity,
          };
          console.log(params)
          request.post('/good/inWarehouse', params)
              .then(response => {
                console.log('入库API响应:', response.data);  // 添加日志
                if (response.data.code === '200') {
                  console.log(response.data)
                  this.$message.success(response.data.data.msg);
                  this.warehouseDialogVisible = false;
                  this.getGoodsInfo();
                } else {
                  this.$message.error(response.data.message || '入库失败');
                }
              })
              .catch(error => {
                console.error('入库失败:', error);
                this.$message.error('入库失败');
              });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    // 提交出库表单
    submitOutForm() {
      this.$refs.outFormRef.validate((valid) => {
        if (valid) {
          this.$confirm('确定要出库吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            request.post('/good/outWarehouse', {
              gid: this.outForm.gid,
              num: this.outForm.quantity
            }).then(response => {
              if (response.data.code === '200') {
                this.$message.success('出库成功');
                this.outDialogVisible = false;
                this.getGoodsInfo();
              } else {
                this.$message.error(response.data.message || '出库失败');
              }
            }).catch(error => {
              console.error('出库失败:', error);
              this.$message.error('出库失败');
            });
          }).catch(() => {
            // 用户取消操作
          });
        }
      });
    }
  }
}
</script>

<style scoped>
#goodsPage {
  padding: 20px;
}
.search-button-col {
  display: flex;
  justify-content: flex-end;
}
</style>